package cn.nubia.admin.common.shiro;

import cn.nubia.admin.common.springmvc.WebContext;
import cn.nubia.admin.sysconfig.bean.MenuResource;
import cn.nubia.admin.sysconfig.bean.User;
import cn.nubia.admin.sysconfig.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: cnJason
 * Date: 14-11-10
 * Time: 上午10:45
 */
public class UserRealm extends AuthorizingRealm {
    private final static Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> userSet = new HashSet<String>();
        //设置用户权限.
        Integer userId = WebContext.getCachedUserId();

        if (userId == null) {
            return authorizationInfo;
        }
        Set<MenuResource> permissions = userService.findPermission(WebContext.getCachedUserId());
        if (permissions == null) {
            return authorizationInfo;
        }
        WebContext.setPermissionToCache(permissions);
        List<String> permissionStr = new ArrayList<String>();
        for (MenuResource menuResource : permissions) {
            permissionStr.add(menuResource.getPermission());
        }
        userSet.addAll(permissionStr);
        authorizationInfo.setStringPermissions(userSet);
        if (logger.isInfoEnabled()) {
            logger.info("用户权限代码为:" + userSet);
        }

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        if (StringUtils.isEmpty(usernamePasswordToken.getUsername())) {
            throw new AccountException("用户名为空");
        }

        String userName = (String) token.getPrincipal();
        User loginUser = userService.getActiveUser(userName);
        String pwd = loginUser.getPassword();

        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(loginUser, pwd, getName());
        // 登陆用户设置在session
        WebContext.setToCache(WebContext.USER_CONSTANTS, loginUser);
        doGetAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
        return authcInfo ;

    }


    public static void main(String[] args) {
        String cryptedPwd = new Md5Hash("admin").toString();
        System.out.println(cryptedPwd);
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }


}
